package com.rrd.itext.servlet.fileupload;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.rrd.itext.utils.GlobalNames;

public class UploadFileServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    public UploadFileServlet() {
        super();
    }

 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
  
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String templateName = request.getParameter("templateName");

        ServletContext sc = getServletContext();
        RequestDispatcher rd = null;
        
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter(); 
        } catch (IOException e1) {
            e1.printStackTrace();
        }
       
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024 * 1024);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(1024 * 1024 * 50);
        upload.setHeaderEncoding("utf-8");
        upload.setSizeMax(1024 * 1024 * 100);

        List<FileItem> list = null;
        try {
            list = upload.parseRequest(request);
        } catch (FileUploadException e) {
            out.print("Faild to parse the files");
            e.printStackTrace();
            return;
        }

        String path = "";

        File uploadDir = new File(path);
        

        if (!ServletFileUpload.isMultipartContent(request)) {
            out.print("Only support multipart/form-data");
            return;
        }

        Iterator<FileItem> it = list.iterator();
        while (it.hasNext()) {
            FileItem fi = (FileItem) it.next();

            if (fi.isFormField()) {
                String name = fi.getFieldName();
                String content = null;
                try {
                    content = fi.getString("utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                if("templateName".equals(name)){
                    templateName = new String(content);
                    path = request.getSession().getServletContext().getRealPath("resources") + "\\" + templateName;
                    uploadDir = new File(path);
                    if (!uploadDir.exists()) {
                        if (!uploadDir.mkdir()) {
                            out.print("Failed to create the direction");
                            return;
                        }
                    }
                }
                request.setAttribute(name, content);
            }
        }
        it = list.iterator();
        while (it.hasNext()) {
            FileItem fi = (FileItem) it.next();

            if (fi.isFormField()) {
                String name = fi.getFieldName();
                String content = null;
                try {
                    content = fi.getString("utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                if("templateName".equals(name)){
                    templateName = new String(content);
                    if(templateName == null || "".equals(templateName)){
                        out.print("Please type the template name");
                        return;
                    }
                    path = request.getSession().getServletContext().getRealPath("resources") + "\\" + templateName;
                    uploadDir = new File(path);
                    if (!uploadDir.exists()) {
                        if (!uploadDir.mkdir()) {
                            out.print("Failed to create the direction");
                            return;
                        }
                    }
                }
                request.setAttribute(name, content);
            } else {
                try {
                    String pathStr = fi.getName();
                    if (pathStr.trim().equals("")) {
                        continue;
                    }
                    int start = pathStr.lastIndexOf("\\");
                    String fileName = pathStr.substring(start + 1);
                    String name = fi.getFieldName();
                    if("layoutXmlFile".equals(name)){
                        fileName = GlobalNames.LAYOUT_FILE_NAME;
                    }else if("dataXmlFile".equals(name)){
                        fileName = GlobalNames.DATA_FILE_NAME;
                    }
                    File pathDest = new File(path, fileName);
                    fi.write(pathDest);
                    //request.setAttribute(name, fileName);
                } catch (Exception e) {
                    out.print("Failed to upload the files");
                    e.printStackTrace();
                    return;
                } finally {
                    fi.delete();
                }
            }
        }
        rd = sc.getRequestDispatcher("/index.jsp");
        rd.forward(request, response);
    }
}